import Taro, { Component } from '@tarojs/taro'
import {Button, View, Text, ScrollView} from '@tarojs/components'
import {AtFloatLayout, AtList, AtListItem, AtModal, AtModalAction, AtModalContent, AtModalHeader, AtTimeline} from 'taro-ui'
import { Loading, ItemCard } from '@components'
import { connect } from '@tarojs/redux'
import * as actions from '@actions/order'
import jump from '@utils/jump'
import { getWindowHeight } from '@utils/style'
import './orderInfo.scss'

@connect(state => state.order, actions)
class OrderInfo extends Component {

  config = {
    navigationBarTitleText: '订单详情',
    enablePullDownRefresh: true,
    backgroundTextStyle: 'dark'
  }

  constructor (props) {
    super(props)
    this.state = {
      loading: true,
      openService: false,
      serviceItem: {},
      openLogistics: false,
      orderTrack: []
    }
    this.orderNo = this.$router.params.orderNo
  }

  componentDidShow() {
    this.setState({ loading: true })
    this.loadOrder(this.orderNo)
  }

  onPullDownRefresh() {
    this.loadOrder(this.orderNo)
    Taro.stopPullDownRefresh()
  }

  loadOrder(orderNo) {
    this.props.dispatchOrderInfo({orderNo: orderNo}).then(() => {
      this.setState({ loading: false })
    })
  }

  handleCancel = (orderNo) => {
    Taro.showModal({
      title: '',
      content: '确定取消此订单？',
      confirmColor: '#E32D2F',
      cancelText: '取消',
      confirmText: '确认'
    }).then(res => {
      if (res.confirm) {
        this.setState({ loading: true })
        this.props.dispatchOrderCancel({orderNo: orderNo}).then(() => {
          this.loadOrder(orderNo);
        }).catch(() => {
          Taro.showToast({
            title: '订单取消失败',
            icon: 'none'
          })
        })
      }
    })
  }

  handlePay = (orderNo) => {
    this.props.dispatchOrderPay({orderNo: orderNo}).then( (payData) => {
      Taro.requestPayment(payData.pay).then(res => {
        Taro.navigateTo({
          url: '/pages/payResult/payResult?msg=' + res.errMsg + '&orderNo=' + orderNo + '&payAmount=' + payData.order.payAmount
        })
      }).catch((err) => {
        if ('requestPayment:fail cancel' != err.errMsg) {
          Taro.navigateTo({
            url: '/pages/payResult/payResult?msg=' + err.errMsg + '&orderNo=' + orderNo + '&payAmount=' + payData.order.payAmount
          })
        }
      })
    })
  }

  handleConfirm = (orderNo) => {
    Taro.showModal({
      title: '',
      content: '是否收到订单商品？',
      confirmColor: '#E32D2F',
      cancelText: '取消',
      confirmText: '确认'
    }).then(res => {
      if (res.confirm) {
        this.setState({ loading: true })
        this.props.dispatchOrderConfirm({orderNo: orderNo}).then(() => {
          this.loadOrder(orderNo);
        }).catch(() => {
          Taro.showToast({
            title: '订单确认失败',
            icon: 'none'
          })
        })
      }
    })
  }

  handleDelete = (orderNo) => {
    Taro.showModal({
      title: '',
      content: '确定删除此订单？',
      confirmColor: '#E32D2F',
      cancelText: '取消',
      confirmText: '确认'
    }).then(res => {
      if (res.confirm) {
        this.props.dispatchOrderDelete({orderNo: orderNo}).then(() => {
          Taro.navigateBack({ delta: 1 })
        }).catch(() => {
          Taro.showToast({
            title: '订单删除失败',
            icon: 'none'
          })
        })
      }
    })
  }

  handleService = (item) => {
    this.setState({
      openService: true,
      serviceItem: item
    })
  }

  handleCloseService = () => {
    this.setState({ openService: false })
  }

  handleClickService = (type) => {
    jump({
      url: '/pages/afterSale/afterSale',
      payload: {
        type: type,
        orderNo: this.orderNo,
        item: JSON.stringify(this.state.serviceItem)
      },
      login: true
    })
    this.handleCloseService()
  }

  handlePhoneCall = () => {
    Taro.makePhoneCall({
      phoneNumber: '17620373226'
    })
  }

  handleLogistics = (orderNo) => {
    this.props.dispatchOrderLogistics({orderNo: orderNo}).then( data => {
      const orderTrack = []
      data.trackList.map((item, index) => {
        const color = index === 0 ? 'red' : 'black'
        const icon = (index === 0 && data.isFinish) ? 'check-circle' : ''
        orderTrack.push({
          title: item.context, content: [item.time], color: color, icon: icon
        });
      })
      this.setState({ openLogistics: true, orderTrack: orderTrack})
    })
  }

  render () {
    const { orderInfo } = this.props
    const { orderNo, orderStatus, itemList = []} = orderInfo
    const showService = orderStatus === '已完成'

    if (this.state.loading) {
      return <Loading />
    }

    return (
      <View className='order-info'>
        <ScrollView
          scrollY
          className='order-info__wrap'
          style={{ height: getWindowHeight(false) }}
        >

          <View className='address__item'>
            <View className='address__item-l'>
              <View className='address__item-name'>{orderInfo.consignee}</View>
            </View>
            <View className='address__item-c'>
              <View className='address__item-mobile'>{orderInfo.phone}</View>
              <View className='address__item-address'>{orderInfo.address}</View>
            </View>
          </View>

          <View className='order-info__status'>
            {orderStatus}
          </View>

          <View className='order-info__list'>
            {itemList.map((item) => (
              <ItemCard key={item.skuId} item={item} showFooter={showService} >
                <View className='order-btn' onClick={this.handleService.bind(this, item)}>
                  <Text className='order-btn-txt'>申请售后</Text>
                </View>
              </ItemCard>
            ))}
          </View>

          <View className='order-info__card'>
            <View className='order-info__card-item'>
              <View className='order-info__txt-name' style='width:25%'>订单编号:</View>
              <View className='order-info__txt-value'>{orderNo}</View>
            </View>
            <View className='order-info__card-item'>
              <View className='order-info__txt-name' style='width:25%'>下单时间:</View>
              <View className='order-info__txt-value'>{orderInfo.createTime}</View>
            </View>
            {
              orderInfo.sendTime &&
              <View className='order-info__card-item'>
                <View className='order-info__txt-name' style='width:25%'>发货时间:</View>
                <View className='order-info__txt-value'>{orderInfo.sendTime}</View>
              </View>
            }
            {
              orderInfo.confirmTime &&
              <View className='order-info__card-item'>
                <View className='order-info__txt-name' style='width:25%'>完成时间:</View>
                <View className='order-info__txt-value'>{orderInfo.confirmTime}</View>
              </View>
            }
          </View>

          <View className='order-info__card'>
            <View className='order-info__price'>
              <View className='order-info__price-l' >商品总额</View>
              <View className='order-info__price-r'>{'¥' + orderInfo.totalAmount}</View>
            </View>
            <View className='order-info__price'>
              <View className='order-info__price-l' >运费</View>
              <View className='order-info__price-r'>{'+ ¥' + orderInfo.freight}</View>
            </View>
            <View className='order-info__price'>
              <View className='order-info__price-l' >优惠券</View>
              <View className='order-info__price-r'>{'- ¥' + orderInfo.couponAmount}</View>
            </View>
            <View className='order-info__price'>
              <View className='order-info__price-l' ></View>
              <View className='order-info__price-r' >
                <Text className='order-info__txt-name' >实付款: </Text>
                <Text className='order-info__txt-primary'>{'¥' + orderInfo.payAmount}</Text>
              </View>
            </View>
          </View>

          <View className='order-info__card'>
            <Text className='order-info__txt-small'>服务时间: </Text><Text className='order-info__txt-narmal'>8:00-24:00</Text>
            <View className='order-info__btn-wrap'>
              <Button
                type='secondary'
                openType='contact'
                className='order-info__btn order-info__btn-l'
                onClick={this.handleAdd}
              >
                <Text className='order-info__btn-txt'>在线客服</Text>
              </Button>

              <Button
                type='secondary'
                className='order-info__btn order-info__btn-r'
                onClick={this.handlePhoneCall.bind(this)}
              >
                <Text className='order-info__btn-txt'>电话客服</Text>
              </Button>
            </View>
          </View>

        </ScrollView>

        {
          {
            '待付款':
              <View className='order-footer'>
                <View className='order-btn' onClick={this.handleCancel.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>取消订单</Text>
                </View>
                <View className='order-btn order-btn--active' onClick={this.handlePay.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>去支付</Text>
                </View>
              </View>,
            '待发货':
              <View className='order-footer'>
                <View className='order-btn' onClick={this.handleCancel.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>取消订单</Text>
                </View>
              </View>,
            '待收货':
              <View className='order-footer'>
                <View className='order-btn' onClick={this.handleLogistics.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>查看物流</Text>
                </View>
                <View className='order-btn' onClick={this.handleConfirm.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>确认收货</Text>
                </View>
              </View>,
            '已取消':
              <View className='order-footer'>
                <View className='order-btn' onClick={this.handleDelete.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>删除订单</Text>
                </View>
              </View>,
            '已完成':
              <View className='order-footer'>
                <View className='order-btn' onClick={this.handleLogistics.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>查看物流</Text>
                </View>
                <View className='order-btn' onClick={this.handleDelete.bind(this, orderNo)}>
                  <Text className='order-btn-txt'>删除订单</Text>
                </View>
                {/*<View className='order-btn--active'>*/}
                {/*  <Text className='order-btn-txt'>评价晒单</Text>*/}
                {/*</View>*/}
              </View>
          }[orderStatus]
        }

        <AtFloatLayout isOpened={this.state.openService} onClose={this.handleCloseService} title='选择售后类型'>
          <AtList>
            <AtListItem title='退货' onClick={this.handleClickService.bind(this, 1)} arrow='right' />
            <AtListItem title='换货' onClick={this.handleClickService.bind(this, 2)} arrow='right' />
          </AtList>
        </AtFloatLayout>

        <AtModal isOpened={this.state.openLogistics} >
          <AtModalHeader>订单跟踪</AtModalHeader>
          <AtModalContent>
            <AtTimeline
              items={this.state.orderTrack}
            >
            </AtTimeline>
          </AtModalContent>
          <AtModalAction></AtModalAction>
        </AtModal>
      </View>
    )
  }
}

export default OrderInfo
